package com.nami.store.biz.groupmembs.service;


import cn.hutool.core.collection.CollUtil;
import com.nami.store.api.request.grpmember.GrpMemberAddReq;
import com.nami.store.api.response.groupmember.GroupMemberDTO;
import com.nami.store.biz.groupmembs.convert.GroupMemberConvert;
import com.nami.store.biz.groupmembs.repository.GroupMemberRepository;
import com.nami.store.domain.GroupMemberDO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

@Slf4j
@Service
@RequiredArgsConstructor
public class GrpMembDomainServiceImpl implements GrpMembDomainService {

    private final GroupMemberRepository memberRepository;

    @Override
    public boolean batchSave(List<GrpMemberAddReq> addRequests) {
        return memberRepository.batchSave(GroupMemberConvert.INSTANCE.convertList2(addRequests));
    }

    @Override
    public GroupMemberDTO getGrpMembersByGrpIdAndUserId(String grpId, String userId) {
        GroupMemberDO grpMember = memberRepository.getGrpMember(grpId, userId);
        return GroupMemberConvert.INSTANCE.convert(grpMember);
    }

    @Override
    public List<GroupMemberDTO> getGrpMembers(String grpId) {
        List<GroupMemberDO> grpMembers = memberRepository.getGrpMembers(grpId);
        return GroupMemberConvert.INSTANCE.convertList(grpMembers);
    }

    @Override
    public List<GroupMemberDTO> getGrpMembersExceptMe(String grpId, String userId) {
        List<GroupMemberDTO> grpMembers = this.getGrpMembers(grpId);
        if (CollUtil.isEmpty(grpMembers)) {
            return null;
        }
        List<GroupMemberDTO> otherMembers = grpMembers.stream().filter(item -> !userId.equals(item.getUserId())).collect(Collectors.toList());
        if (CollUtil.isEmpty(otherMembers)) {
            return null;
        }
        return otherMembers;
    }

    @Override
    public List<GroupMemberDTO> getGrpMembsByGrpIdAndUserIds(String grpId, List<String> userIds) {
        List<GroupMemberDO> grpMembers = memberRepository.getGrpMembers(grpId, userIds);
        if (CollUtil.isEmpty(grpMembers)) {
            return null;
        }
        return GroupMemberConvert.INSTANCE.convertList(grpMembers);
    }

    @Override
    public Map<String, GroupMemberDTO> getGrpMembsByUserIds(String grpId, List<String> userIds) {
        List<GroupMemberDTO> list = this.getGrpMembsByGrpIdAndUserIds(grpId, userIds);
        if (CollUtil.isEmpty(list)) {
            return new HashMap<>();
        }
        return list.stream().collect(Collectors.toMap(GroupMemberDTO::getUserId, Function.identity()));
    }
}
